﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace org.webguvenligi.NSecureImageLib.GraphicFileFormats.JPEG
{
    class YuvConvertor
    {
        
        static readonly double[][] r2y = new double[][]{ 
                                   new double[] { 0.299, 0.587, 0.114 },
                                   new double[] { -0.1687, -0.3313, 0.5 },
                                   new double[] {0.5, -0.4187, -0.0813}};  
        
        static readonly double[][] y2r = new double[][]{
                                   new double[]{1, 0, 1.402},
                                   new double[]{1, -0.34414, -0.71414},
                                   new double[]{1, 1.772, 0}};

        public static void rgb2yuv(int[] rgb, int[] yuv)
        {
         for (int i=0; i<3; i++) {
            double sum=0;
            for (int j = 0; j < 3; j++)
            {
                sum += r2y[i][j] * (rgb[j] - 128);
            }
            yuv[i]=Convert.ToInt32(sum+0.5);
         }
       }

        public static void yuv2rgb(int[] yuv, int[] rgb) {
            for (int i=0;i<3;i++) {
                double sum=0;
                for (int j = 0; j < 3; j++)
                {
                    sum += y2r[i][j] * yuv[j];
                }
                rgb[i]=Convert.ToInt32(sum+0.5);
                rgb[i]+=128;
                if (rgb[i] < 0)
                {
                    rgb[i] = 0;
                }
                else if (rgb[i] > 255)
                {
                    rgb[i] = 255;
                }
            }
        }
    }
}